package org.huangxq.bigscreen.controller.config

import jakarta.annotation.Resource
import org.huangxq.bigscreen.data.DataBaseData
import org.huangxq.bigscreen.service.DataBaseService
import org.slf4j.LoggerFactory
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

/**
@Description: 数据源配置请求
@author: 黄显清
@Date: 2022-07-21
@version： 1.0
 */

@RestController
@RequestMapping("/config/database")
class DataBaseController {

    private val log = LoggerFactory.getLogger("log")

    @Resource
    private lateinit var dataBaseService: DataBaseService

    /**
     * 	数据库信息保存
     * @param:  String
     * @return: String
     */
    @RequestMapping("/save")
    fun save(@RequestBody dataBase: DataBaseData) = try {
        dataBaseService.save(dataBase)
        "success"
    }catch (e: Exception){
        log.error(e.toString())
        e.toString()
    }

    /**
     * 	数据库信息删除
     * @param:  String
     * @return: String
     */
    @RequestMapping("/delete")
    fun delete(id: String) = try {
        dataBaseService.delete(id)
        "success"
    }catch (e: Exception){
        log.error(e.toString())
        e.toString()
    }

    /**
     * 	数据库信息获取
     * @param:  String
     * @return: String
     */
    @RequestMapping("/getOne")
    fun getOne(id: String) = try {
        val db = dataBaseService.getOne(id)
        log.debug(db.toString())
        mapOf(
            "status" to 200,
            "data" to db
        )
    }catch (e: Exception){
        log.error(e.toString())
        mapOf(
            "status" to -1,
            "data" to e.toString()
        )
    }

    /**
     *  获取全部数据库信息
     *  @return: String
     */
    @RequestMapping("/list")
    fun list() = try{
        val dbs = mutableListOf<DataBaseData>()
        for (db in dataBaseService.list()){
            val tarDB = DataBaseData(
                db.id, db.name, db.type, db.port, db.ip, db.user, "", db.serv
            )
            dbs.add(tarDB)
        }
        mapOf(
            "status" to 200,
            "data" to dbs
        )
    }catch (e: Exception){
        log.error(e.toString())
        mapOf(
            "status" to -1,
            "data" to e.toString()
        )
    }

    /**
     *  数据库连接测试
     */
    @RequestMapping("/test")
    fun test(@RequestBody dataBase: DataBaseData) = try {
        log.info(dataBase.toString())
        dataBaseService.test(dataBase)
        "success"
    }catch (e: Exception){
        log.error(e.toString())
        e.toString()
    }
}